/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

package com.huawei.api.builder;

import com.alibaba.fastjson.JSONArray;
import com.huawei.api.bean.Language;
import com.huawei.api.exception.BaseCustomerException;
import com.huawei.api.utils.FileUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 语言配置加载
 *
 * @since 2023/10/28
 */
@Data
public class LanguageCfgBuilder implements Builder {
    private static final Logger LOGGER = LoggerFactory.getLogger(LanguageCfgBuilder.class);

    private final String languageCfgPath;

    private final List<Language> languages;

    public LanguageCfgBuilder(String languageCfgPath) {
        this.languageCfgPath = languageCfgPath;
        this.languages = new ArrayList<>();
    }

    @Override
    public void build() throws BaseCustomerException {
        LOGGER.info("-----------------LanguageCfgBuilder start build---------------------------");
        boolean isExists = FileUtil.fileIsExists(languageCfgPath);
        // 没有配置规则文件则读取，默认的规则文件
        if (!isExists) {
            loadDefaultLanguage();
        } else {
            loadCustomLanguage();
        }
    }

    private void loadDefaultLanguage() throws BaseCustomerException{
        // 读取默认语言工具文件内容，json转化为对象
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("language.json");
        if (inputStream == null) {
            return;
        }
        try {
            String content = FileUtil.getResourceFileContent(inputStream);
            if (StringUtils.isBlank(content)){
                return;
            }
            JSONArray jsonArray = JSONArray.parseArray(content.toString());
            List<Language> languageList = jsonArray.toJavaList(Language.class);
            languages.addAll(languageList);
        } catch (BaseCustomerException exception) {
            LOGGER.debug("some error occur in default language config builder");
            throw new BaseCustomerException("load default language config error");
        }
    }

    private void loadCustomLanguage() throws BaseCustomerException{
        try {
            String content = FileUtil.getFileContent(languageCfgPath);
            if (StringUtils.isBlank(content)){
                return;
            }
            JSONArray jsonArray = JSONArray.parseArray(content.toString());
            List<Language> languageList = jsonArray.toJavaList(Language.class);
            languages.addAll(languageList);
        } catch (BaseCustomerException exception) {
            LOGGER.debug("some error occur in custom language config builder");
            throw new BaseCustomerException("load custom rule config error");
        }
    }
}
